import { useEffect, useState } from 'react'
import loginTitleIcon from '../assets/loginTitleIcon.png'
import { Button, Form, Input, Space, Typography, message } from 'antd'
import { CheckCircleFilled } from '@ant-design/icons'
import ProductList from '../components/ProductList'
import ShoppingCart from '../components/ShoppingCart'
import Copyright from '../components/Copyright'
import Banner from '../components/Banner'
import Navigator from '../components/Navigator'
import LeftCont from '../components/LeftCont'
import { useNavigate } from 'react-router-dom'
import Kefu from '../components/Kefu'
import '../App.scss'
import { loginAPI, sendCodeAPI } from '../service/user'
import { setStorage, setToken } from '../utils/tools'

function PcIndex() {
  // 路由跳转
  const navigate = useNavigate()
  const [disabled, setDisabled] = useState(false);
  const [countdown, setCountdown] = useState(60);
  const [timer, setTimer] = useState(null);
  const [checked, setChecked] = useState(false)
  const [phone, setPhone] = useState('')
  // 点击发送验证码 
  const handleClick = async() => {
    // 获取用户输入的手机号码 如果手机号码格式 不正确，提示错误信息并返回
    if (!/^1[3456789]\d{9}$/.test(phone)) {
      message.error('请输入正确的手机号码');
      return;
    }
    
    if (disabled) return; // 如果按钮已禁用，则不执行任何操作

    // 发送验证码逻辑
    const res = await sendCodeAPI({ phone });
    console.log(res)
    if (res.status === 200) {
      // 将提示消息显示3秒钟
      message.success({
        content: '验证码发送成功',
        duration: 3, // 显示3秒
      });
    } else {
      message.error('发送失败：' + res.data.message);
      return false
    }

    // 设置按钮为禁用状态
    setDisabled(true);
    setCountdown(60); // 重置倒计时

    // 设置倒计时
    const interval = setInterval(() => {
      setCountdown(prevCountdown => {
        if (prevCountdown === 0) {
          // 如果倒计时为0，清除定时器并重置按钮状态
          clearInterval(interval);
          setDisabled(false);
          return 60; // 重置倒计时状态
        }
        return prevCountdown - 1; // 否则递减倒计时
      });
    }, 1000);
    setTimer(interval);
  }
  // 登录逻辑
  const login = async (values) => {
    // 先接收许可协议
    if (!checked) {
      message.error('请先阅读并同意许可协议');
      return;
    }
    const { phone, code } = values
    const res = await loginAPI({ phone, code })
    console.log(res)
    if (res.status === 200) {
      message.success('登录成功')
      setToken(res.data.data.authToken)  // 保存token
      setStorage('username', res.data.data.username)  // 保存用户名
      navigate('/home') // 登录成功，跳转到首页
    } else {
      message.error('登录失败，请检查手机号和验证码是否正确') // 登录失败，提示错误信息
    }
  }
  useEffect(() => {
    message.config({
      top: 300
    })
  }, [])
  useEffect(() => {
    return () => {
      if (timer) {
        clearInterval(timer); // 清除定时器
      }
    };
  }, [timer]);
  return (
    <>
      {/* 顶部banner */}
      <Banner />
      {/* 顶部导航 */}
      <Navigator />
      {/* 容器 */}
      <div className="wrapMain">
        {/* 左侧 */}
        <div className="sliderWrap">
          <LeftCont />
          <div className="loginWrap">
            <div className="loginTitle">
              <img src={loginTitleIcon} alt="" />
              <span>账号登录</span>
            </div>
            <div className="formWrap">
              <Form onFinish={login}>
                <Form.Item
                  name="phone"
                  rules={[
                    { required: true, message: '请输入手机号' },
                    // 验证手机号码格式
                    { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号' },
                  ]}
                >
                  <Input
                    placeholder="请输入手机号"
                    size="large"
                    className="myInput"
                    // 保存手机号码
                    onChange={(e) => setPhone(e.target.value)}
                  />
                </Form.Item>
                <Form.Item>
                  <Space.Compact
                    style={{
                      width: '100%'
                    }}
                  >
                    <Form.Item
                      name="code"
                      rules={[
                        { required: true, message: '请输入验证码' },
                        // 验证验证码格式
                        { pattern: /^\d{6}$/, message: '请输入6位验证码' },
                      ]}
                    >
                      <Input size="large" className="myInput" style={{width: 160}} />
                    </Form.Item>
                    <Button
                      style={{
                        backgroundColor: disabled ? 'gray' : '#333',
                        color: '#fff',
                        borderRadius: 0,
                        fontSize: 14,
                        border: 'none',
                        width: 105
                      }}
                      size="large"
                      disabled={disabled}
                      onClick={handleClick}
                    >
                      {disabled ? `${countdown}s` : '发送验证码'}
                    </Button>
                  </Space.Compact>
                </Form.Item>
                <Form.Item style={{marginTop: -20}}>
                  <Button
                    htmlType="submit"
                    block
                    size="large"
                    style={{
                      backgroundColor: '#d34145',
                      color: '#fff',
                      borderRadius: 0,
                      border: 'none'
                    }}
                  >
                    登录
                  </Button>
                </Form.Item>
              </Form>
              <Typography.Paragraph
                style={{
                  fontSize: 12,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'end'
                }}
                className="desc"
              >
                <span onClick={() => setChecked(!checked)}>
                  {checked ?  (
                    <CheckCircleFilled
                      style={{ marginRight: 5, color: '#d34145', fontSize: 16 }}
                    />
                  ) : (
                    <i style={{
                      width: 14,
                      height: 14,
                      border: '3px solid #dedede',
                      borderRadius: '50%',
                      display: 'block',
                      marginRight: 5
                    }}></i>
                  )}
                </span>
                
                
                <span>
                  我已阅读并同意<a href="#">《用户协议》</a>
                  <a href="#">《隐私政策》</a> 
                </span>
              </Typography.Paragraph>
            </div>
          </div>
        </div>
        {/* 右侧 */}
        <div className="rightWrap">
          <div className="rightContainer">
            <div className="rightTitle">
              <span>请选择商品</span>
            </div>
            <div className="rightContent">
              <div className="rightActive">
                <span className="dollarIcon">$</span>
                <span className="text">特别活动</span>
              </div>
              <p className="description">
              每个商品首次购买都可获得该商品额外0.5倍的加赠奖励。<br />
              在官网充值不影响游戏应用内商品的首充奖励次数。
              </p>
              {/* 购物车 */}
              <ProductList />
            </div>
          </div>
          <ShoppingCart />
        </div>
      </div>
      {/* 版权 */}
      <Copyright />
      <Kefu />
    </>
  )
}

export default PcIndex